package impl;

import anaydis.sort.SorterType;

import java.util.Comparator;
import java.util.*;

/**
 * Created by IntelliJ IDEA.
 * User: Keevu
 * Date: 30/09/11
 * Time: 11:09
 * To change this template use File | Settings | File Templates.
 */
public class QuickSorterNoRecursivo extends AbstractSorter {
    public QuickSorterNoRecursivo() {
        super(SorterType.QUICK_NON_RECURSIVE);
    }

     public <T> void sort(Comparator<T> tComparator, List<T> ts){
        List<Integer> pivotes = new ArrayList<Integer>();
        pivotes.add(0);
        pivotes.add(ts.size());
        int i = 0;
        while((i*2)+1<pivotes.size()){
            if(Math.abs(pivotes.get((2*i)+1) - pivotes.get(2*i)) > 2){
                int g = partition(tComparator, ts, pivotes.get(2*i) , pivotes.get((2*i)+1), (pivotes.get((2*i)+1))-1);
                pivotes.add(pivotes.get(2*i));
                pivotes.add(g);
                pivotes.add(g);
                pivotes.add(pivotes.get((2*i)+1));
            }
            i++;
        }
    }


    protected <T> int partition(Comparator<T> tComparator, List<T> ts,int desde, int hasta, int pivote){
        int i = desde;
        int j = hasta-2;
        boolean end = false;
        swap(ts, pivote, hasta-1);
        pivote = hasta-1;
        do{
            boolean imayor = false;
            do{
                if (!greater(tComparator, ts, i,pivote)) {
                    i++;
                } else {
                    imayor = true;
                }
            }while((!imayor) && (i < (j + 1)));
                boolean jmenor = false;
                do{
                    if (greater(tComparator, ts, j,pivote)) {
                        j--;
                    } else {
                        jmenor = true;
                    }
                }while((!jmenor) && i<j+1);
                if(i<j){
                    swap(ts, i, j);
                }
                else{
                    swap(ts,i,pivote);
                    end = true;
                }
        }while(!end);
        return i;
    }
}